function [ inp_data ] = improveDatasetParallel(inp_data, baseline, hogsize)
% See improve_dataset.mat under misc_scripts for usage (this is the
% parallel version)

parfor ix = 1:length(inp_data)
    data = inp_data(ix);
    if ~isempty(data.cam_id)
        disp(['improveDataset: starting image ' num2str(ix)]);
        [ best_rect, best_hog ] = arrayfun(@(x) jitterInstance(data, x, baseline), 1:size(data.ppl_rects,1), 'UniformOutput', false);
        data.ppl_rects = reshape(cell2mat(best_rect), [4 size(data.ppl_rects,1)])';
        data.ppl_hogs = reshape(cell2mat(best_hog), [hogsize size(data.ppl_rects,1)])';
    end
    inp_data(ix) = data;
end

end

function [ best_rect, best_hog ] = jitterInstance(data, rect_ind, baseline)
load_settings;
test_res = data;
test_res.ppl_rects = [];
test_res.ppl_hogs = [];
rect_list = jitterRect(data.ppl_rects(rect_ind,:), jitter_margin, jitter_inc);
test_res.ppl_rects = rect_list;
test_res = checkBounds(test_res);
test_res = computeHogsParallel(test_res, image_root, reshape_size, binsize, hogsize);
[new, ~] = eval_baseline(baseline, test_res.ppl_hogs, ones(size(test_res.ppl_hogs,1),1), settings);
[~, index] = max(new.dv);
best_rect = test_res.ppl_rects(index,:);
best_hog = test_res.ppl_hogs(index,:);
if isempty(best_rect)
    best_rect = data.ppl_rects(rect_ind,:);
    best_hog = data.ppl_hogs(rect_ind,:);
end
end